import shutil
from pathlib import Path
from typing import List, Dict, Any
from ..utils.config import settings
from .dicom_service_optimized import dicom_service

class FileService:
    """文件操作服务"""
    
    @staticmethod
    def save_uploaded_file(file, file_path: Path) -> None:
        """保存上传的文件"""
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file, buffer)
    
    @staticmethod
    def delete_file(file_path: Path) -> bool:
        """删除文件及其相关资源"""
        try:
            # 删除对应的JPEG图像文件夹
            file_name_without_ext = file_path.stem
            img_folder = settings.DICOM_IMG_STORAGE / file_name_without_ext
            if img_folder.exists():
                try:
                    shutil.rmtree(img_folder)
                except Exception as e:
                    print(f"删除JPEG文件夹失败: {str(e)}")
            
            # 删除DICOM文件
            if file_path.exists():
                file_path.unlink()
                return True
            return False
        except Exception as e:
            print(f"删除文件失败: {str(e)}")
            return False
    
    @staticmethod
    def list_dicom_files() -> List[Dict[str, Any]]:
        """列出所有DICOM文件"""
        files = []
        for file in settings.DICOM_STORAGE.glob("*.dcm"):
            try:
                metadata = dicom_service.read_metadata(file)
                files.append({
                    "filename": file.name,
                    "size": file.stat().st_size,
                    "metadata": metadata
                })
            except Exception:
                # 如果文件解析失败，仍然添加基本信息
                files.append({
                    "filename": file.name,
                    "size": file.stat().st_size,
                    "metadata": {"error": "无法解析DICOM元数据"}
                })
        return files
    
    @staticmethod
    def file_exists(file_path: Path) -> bool:
        """检查文件是否存在"""
        return file_path.exists()

# 创建服务实例
file_service = FileService()
